// mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QFileDialog>
#include <QTableWidgetItem>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow),
    m_testCaseManager(new TestCaseManager(this)),
    m_testExecution(new TestExecution(this)),
    m_testCaseEditor(nullptr),
    m_currentTestCaseIndex(-1) {
    ui->setupUi(this);

    // 配置测试案例列表
    ui->testCaseTable->setColumnCount(4);
    ui->testCaseTable->setHorizontalHeaderLabels(QStringList() << "选择" << "测试案例名称" << "测试" << "测试结果");

    // 连接所有信号到槽函数
    connect(m_testExecution, &TestExecution::testProgress,
            this, &MainWindow::onTestProgress);
    connect(m_testExecution, &TestExecution::testCaseFinished,
            this, &MainWindow::onTestCaseFinished);
    connect(m_testExecution, &TestExecution::testCompleted,  // 如需使用
            this, &MainWindow::onTestCompleted);

    // 保存原始中央部件（包含 testCaseTable 的部件）
    m_originalCentralWidget = centralWidget();
    // 初始显示测试案例列表
    refreshTestCaseList();

    // 默认使用UDP通信
    m_currentCommType=1;
    m_testExecution->setProtocol(CommunicationProtocol::UDP);
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::refreshTestCaseList() {
    // 双重检查：确保 ui 和 testCaseTable 有效
    if (!ui || !ui->testCaseTable) {
        qCritical() << "refreshTestCaseList: ui 或 testCaseTable 为空！";
        return;
    }
    ui->testCaseTable->setRowCount(0);

    QList<TestCase> testCases = m_testCaseManager->getTestCases();
    for (int i = 0; i < testCases.size(); ++i) {
        int row = ui->testCaseTable->rowCount();
        ui->testCaseTable->insertRow(row);

        // 勾选框
        QTableWidgetItem* checkItem = new QTableWidgetItem();
        checkItem->setCheckState(Qt::Unchecked);
        ui->testCaseTable->setItem(row, 0, checkItem);

        // 测试案例名称
        QTableWidgetItem* nameItem = new QTableWidgetItem(testCases[i].name);
        ui->testCaseTable->setItem(row, 1, nameItem);

        // 测试按钮
        QPushButton* testBtn = new QPushButton("测试");
        ui->testCaseTable->setCellWidget(row, 2, testBtn);

        connect(testBtn, &QPushButton::clicked, [=]() {
            m_currentTestCaseIndex = i;
            m_testExecution->executeTestCase(testCases[i],i);
        });

        // 测试结果
        QTableWidgetItem* resultItem = new QTableWidgetItem(testCases[i].testResult);
        ui->testCaseTable->setItem(row, 3, resultItem);
    }
}

QList<int> MainWindow::getSelectedTestCases() {
    QList<int> selectedIndices;

    for (int i = 0; i < ui->testCaseTable->rowCount(); ++i) {
        QTableWidgetItem* checkItem = ui->testCaseTable->item(i, 0);
        if (checkItem && checkItem->checkState() == Qt::Checked) {
            selectedIndices.append(i);
        }
    }

    return selectedIndices;
}

void MainWindow::on_actionTestCaseEditor_triggered() {
    if (!m_testCaseEditor) {
        m_testCaseEditor = new TestCaseEditor(m_testCaseManager, this);
        connect(m_testCaseEditor, &TestCaseEditor::backToTestList,
                this, &MainWindow::on_backFromEditor);
    }
    m_originalCentralWidget->hide();
    m_testCaseEditor->show();
}

void MainWindow::on_testSelectedBtn_clicked() {
    QList<int> selectedIndices = getSelectedTestCases();

    if (selectedIndices.isEmpty()) {
        QMessageBox::information(this, "提示", "请先选择要测试的案例");
        return;
    }

    for(int i=0;i<selectedIndices.size();i++)
    {
        m_currentTestCaseIndex = selectedIndices[i];
        QList<TestCase> testCases = m_testCaseManager->getTestCases();
        m_testExecution->executeTestCase(testCases[m_currentTestCaseIndex],m_currentTestCaseIndex);
    }
}

void MainWindow::on_selectAllBtn_clicked() {
    /*
    Qt::CheckState state = Qt::Checked;

    // 检查是否已经全选
    for (int i = 0; i < ui->testCaseTable->rowCount(); ++i) {
        QTableWidgetItem* checkItem = ui->testCaseTable->item(i, 0);
        if (checkItem && checkItem->checkState() != Qt::Checked) {
            state = Qt::Checked;
            break;
        }
        state = Qt::Unchecked;
    }

    // 设置所有勾选框状态
    for (int i = 0; i < ui->testCaseTable->rowCount(); ++i) {
        QTableWidgetItem* checkItem = ui->testCaseTable->item(i, 0);
        if (checkItem) {
            checkItem->setCheckState(state);
        }
    }
    */
    QList<TestCase> testCases = m_testCaseManager->getTestCases();
    for(int i=0;i<testCases.size();i++)
    {
        m_testExecution->executeTestCase(testCases[i],i);
    }
}

void MainWindow::onTestCaseTested(const QString& result) {
    if (m_currentTestCaseIndex >= 0) {
        QList<TestCase> testCases = m_testCaseManager->getTestCases();
        if (m_currentTestCaseIndex < testCases.size()) {
            testCases[m_currentTestCaseIndex].testResult = result;
            m_testCaseManager->setTestCases(testCases);
            m_testCaseManager->saveTestCases();
            refreshTestCaseList();
        }

        // 检查是否有更多选中的测试案例需要执行
        QList<int> selectedIndices = getSelectedTestCases();
        int currentIndex = selectedIndices.indexOf(m_currentTestCaseIndex);

        if (currentIndex + 1 < selectedIndices.size()) {
            m_currentTestCaseIndex = selectedIndices[currentIndex + 1];
            m_testExecution->executeTestCase(testCases[m_currentTestCaseIndex],m_currentTestCaseIndex);
        } else {
            m_currentTestCaseIndex = -1;
        }
    }
}

void MainWindow::on_backFromEditor() {
    if (m_testCaseEditor) {
        // 隐藏编辑界面，恢复原始中央部件（关键：确保 testCaseTable 所在部件有效）
        m_originalCentralWidget->show();
        m_testCaseEditor->hide();  // 仅隐藏，不销毁（避免重复创建）
    }

    // 刷新列表前，先检查 testCaseTable 是否有效
    if (!ui || !ui->testCaseTable) {
        qCritical() << "错误：ui->testCaseTable 为空，无法刷新列表！";
        return;
    }
    refreshTestCaseList();
}

void MainWindow::on_editTestCaseBtn_clicked()
{
    // 如果编辑界面未创建，则创建；否则直接显示
    if (!m_testCaseEditor) {
        m_testCaseEditor = new TestCaseEditor(m_testCaseManager, this);
        // 连接编辑界面的“返回”信号，关闭后回到主界面
        connect(m_testCaseEditor, &TestCaseEditor::backToTestList,
                this, &MainWindow::on_backFromEditor,Qt::QueuedConnection);
    }
    // 显示编辑界面（替换主窗口中央部件）
    m_originalCentralWidget->hide();
    m_testCaseEditor->show();
}

void MainWindow::on_exportCsvBtn_clicked()
{
    // 弹出文件选择对话框，让用户选择保存路径
    QString filePath = QFileDialog::getSaveFileName(
        this,
        "导出测试结果到CSV",
        QString("TestResult_%1.csv").arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss")),
        "CSV文件 (*.csv)"
        );

    if (!filePath.isEmpty()) {
        // 调用TestExecution的导出方法（假设m_testExecution是MainWindow的成员变量）
        m_testExecution->exportTestResultsToCsv(filePath);
        QMessageBox::information(this, "导出成功", QString("CSV文件已保存至：\n%1").arg(filePath));
    }

}

// 2. 实现进度更新槽函数（实时显示测试过程）
void MainWindow::onTestProgress(int caseIndex, const QString& status) {
    if (caseIndex < 0 || caseIndex >= ui->testCaseTable->rowCount()) {
        qWarning() << "无效的测试案例索引:" << caseIndex;
        return;
    }

    // 更新"测试结果"列（第3列）为当前进度
    QTableWidgetItem* resultItem = ui->testCaseTable->item(caseIndex, 3);
    if (!resultItem) {
        resultItem = new QTableWidgetItem();
        ui->testCaseTable->setItem(caseIndex, 3, resultItem);
    }
    resultItem->setText(status);
    resultItem->setForeground(QBrush(Qt::blue)); // 进度用蓝色
    ui->testCaseTable->resizeRowToContents(caseIndex);  // 自动调整行高
}

// 3. 完善最终结果槽函数（测试完成后显示最终结果）
void MainWindow::onTestCaseFinished(int caseIndex, const QString& result) {
    if (caseIndex < 0 || caseIndex >= ui->testCaseTable->rowCount()) {
        QMessageBox::warning(this, tr("警告"), tr("无效的测试用例索引: %1").arg(caseIndex));
        return;
    }

    // 更新"测试结果"列为最终结果
    QTableWidgetItem* resultItem = ui->testCaseTable->item(caseIndex, 3);
    if (!resultItem) {
        resultItem = new QTableWidgetItem();
        ui->testCaseTable->setItem(caseIndex, 3, resultItem);
    }
    resultItem->setText(result);
    // 根据结果设置颜色
    resultItem->setForeground(QBrush(result.contains("所有组测试通过") ? Qt::green : Qt::red));
    ui->testCaseTable->resizeRowToContents(caseIndex);

    // 保存结果到测试案例管理器（可选）
    QList<TestCase> testCases = m_testCaseManager->getTestCases();
    if (caseIndex < testCases.size()) {
        testCases[caseIndex].testResult = result;
        m_testCaseManager->setTestCases(testCases);
        m_testCaseManager->saveTestCases();
    }
}

// 4. 可选：处理中间步骤完成信号（如需显示更细粒度的结果）
void MainWindow::onTestCompleted(int caseIndex, const QString& result) {
    // 示例：在进度和最终结果之间显示中间结果
    onTestProgress(caseIndex, "步骤完成: " + result);
}

void MainWindow::on_swithTypeBtn_clicked()
{
    if(m_currentCommType==1)
    {
        m_testExecution->setProtocol(CommunicationProtocol::TRDP);
        m_currentCommType=2;
        ui->lableCurType->setText("TRDP");
    }
    else if(m_currentCommType==2)
    {
        m_testExecution->setProtocol(CommunicationProtocol::UDP);
        m_currentCommType=1;
        ui->lableCurType->setText("UDP");
    }
}

